<template>
  <div>
    <el-form ref="form" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId" value="value">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="tm in trademarkList"
            :key="tm.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" rows="3" v-model="spu.description"></el-input>
      </el-form-item>
      <!-- 照片墙 -->
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="imageList"
          :on-success="handlerSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${unSelectSaleAttr.length}未选择`"
          v-model="attrIdAndAttrName"
        >
          <el-option
            :label="saleAttr.name"
            :value="`${saleAttr.id}:${saleAttr.name}`"
            v-for="saleAttr in unSelectSaleAttr"
            :key="saleAttr.id"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          @click="addSaleAttr"
          :disabled="unSelectSaleAttr.length == 0"
          >添加属性</el-button
        >
      </el-form-item>

      <el-form-item>
        <!-- 最下面表格 -->
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column
            prop="prop"
            label="序号"
            width="80"
            type="index"
            align="center"
          ></el-table-column>
          <!-- 第二列 属性名列表 -->
          <el-table-column
            prop="saleAttrName"
            label="属性名"
            width="width"
          ></el-table-column>
          <!-- 第三列 属性名称列表 -->
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row, $index }">
              <!-- tag标签 -->
              <el-tag
                :key="attr.id"
                v-for="attr in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="handleClose(row, attr.saleAttrValueName)"
              >
                {{ attr.saleAttrValueName }}
              </el-tag>

              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @blur="handleInputConfirm(row)"
                @keyup.enter.native="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >添加属性</el-button
              >
            </template>
          </el-table-column>
          <!-- 第四列 操作 -->
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                title="删除"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script>
export default {
  name: "SpuForm",
  components: {},
  data() {
    return {
      //spu属性初始化的时候是一个空的对象,在修改SPU的时候，会想服务器发请求，返回SPU信息（对象），在修改的时候可以利用服务器返回的这个对象收集最新的数据提交给服务器
      //添加SPU，如果是添加SPU的时候并没有向服务器发请求，数据收集到哪里呀[SPU]，收集数据的时候有哪些字段呀，看文档
      spu: {
        //三级分类的id
        category3Id: 0,
        //描述
        description: "",
        //spu名称
        spuName: "",
        //平台的id
        tmId: "",
        //收集SPU图片的信息
        spuImageList: [],
        //平台属性与属性值收集
        spuSaleAttrList: [],
      },
      dialogImageUrl: "",
      dialogVisible: false,

      trademarkList: [],
      imageList: [],
      saleAttr: [],
      attrIdAndAttrName: "", //收集未选择的销售属性的id-----
    };
  },
  computed: {
    unSelectSaleAttr() {
      return this.saleAttr.filter((item) => {
        return this.spu.spuSaleAttrList.every((items) => {
          return item.name != items.saleAttrName;
        });
      });
    },
  },
  methods: {
    //添加Spu只需要发送两次请求即可
    async addSpuData(category3Id) {
      console.log(category3Id, "3Id");
      //添加SPU的时候收集三级分类的id
      this.spu.category3Id = category3Id;
      //获取品牌的信息
      let tradeMarkResult = await this.$API.spu.reqTrademarkList();
      if (tradeMarkResult.code == 200) {
        this.trademarkList = tradeMarkResult.data;
      }
      //获取平台全部的销售属性
      let saleResult = await this.$API.spu.reqSaleSku();
      if (saleResult.code == 200) {
        this.saleAttr = saleResult.data;
      }
    },
    //添加或者修改Spu(保存按钮回调)
    async addOrUpdateSpu() {
      this.spu.spuImageList = this.imageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: (item.response && item.response.data) || item.url,
        };
      });
      console.log(this.spu.spuImageList, "地址测试");
      console.log(this.imageList, "地址测试2");

      //发请求
      let result = await this.$API.spu.reqAddOrUpdateSpu(this.spu);
      if (result.code == 200) {
        //提示
        this.$message({ type: "success", message: "保存成功" });
        //通知父组件回到场景1
        this.$emit("hideSpuForm", {
          isShow: 1,
          flag: this.spu.id ? "修改" : "添加",
        });
      }
      //清除数据
      Object.assign(this._data, this.$options.data());
    },
    //取消按钮
    cancel() {
      //取消按钮的回调，通知父亲切换场景为0
      this.$emit("hideSpuForm", { isShow: 1, flag: "" });
      //清理数据
      //Object.assign:es6中新增的方法可以合并对象
      //组件实例this._data,可以操作data当中响应式数据
      //this.$options可以获取配置对象，配置对象的data函数执行，返回的响应式数据为空的
      Object.assign(this._data, this.$options.data());
    },
    //添加销售属性
    addSaleAttr() {
      //把收集到的销售属性数据进行分割
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(":");
      //向SPU对象的spuSaleAttrList属性里面添加新的销售属性
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      //添加新的销售属性
      this.spu.spuSaleAttrList.push(newSaleAttr);
    },
    //删除图片时的回调
    handleRemove(file, fileList) {
      this.imageList = fileList;
      console.log(file, fileList);
    },
    //图片上传成功时的回调
    handlerSuccess(response, file, fileList) {
      this.imageList = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //删除面包屑的回调
    handleClose(row, saleAttrValueName) {
      console.log(row, saleAttrValueName);
      row.spuSaleAttrValueList = row.spuSaleAttrValueList.filter((item) => {
        return item.saleAttrValueName != saleAttrValueName;
      });
    },
    //显示input
    showInput(row) {
      this.$set(row, "inputVisible", true);
      console.log(row.inputVisible, "测试row");
      this.$set(row, "inputValue", "");
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //input失去焦点的时候触发的回调
    handleInputConfirm(row) {
      console.log(row, "失去焦点");
      //解构出销售属性当中收集数据
      const { baseSaleAttrId, inputValue } = row;
      //新增的销售属性值的名称不能为空
      if (inputValue.trim() == "") {
        this.$message("属性值不能为空");
        return;
      }

      let result = row.spuSaleAttrValueList.every(
        (item) => item.saleAttrValueName != inputValue
      );
      if (!result) return;
      //新增的销售属性值
      let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue };
      //新增
      row.spuSaleAttrValueList.push(newSaleAttrValue);

      row.inputVisible = false;
    },

    //发送请求获取信息
    async initSpuData(spu) {
      //获取spu信息数据
      let resultSpu = await this.$API.spu.reqSpuInfo(spu.id);
      if (resultSpu.code == 200) {
        this.spu = resultSpu.data;
      }
      //获取品牌数据
      let resultTrademarkList = await this.$API.spu.reqTrademarkList();
      if (resultTrademarkList.code == 200) {
        this.trademarkList = resultTrademarkList.data;
      }

      //获取图片数据
      let resultSpuImage = await this.$API.spu.reqSpuImage(spu.id);
      if (resultSpuImage.code == 200) {
        let listArr = resultSpuImage.data;
        //由于照片墙显示图片的数据需要数组，数组里面的元素需要有name与url字段
        //需要把服务器返回的数据进行修改
        listArr.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        //把整理好的数据赋值给
        this.imageList = listArr;
      }

      //获取平台全部销售属性
      let resultSaleSku = await this.$API.spu.reqSaleSku();
      if (resultSaleSku.code == 200) {
        this.saleAttr = resultSaleSku.data;
      }
    },
  },
};
</script>


<style >
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>